package Util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;



public class DBUtil {
    //初始化连接池
    private static BasicDataSource basicDataSource=new BasicDataSource();
    //初始化properties对象
    private static Properties properties=new Properties();
    //设置数据库和连接池变量
    private static String driver;
    private static String url;
    private static String user;
    private static String pwd;
    private static String initialSize;
    private static String maxIdle;
    private static String minIdle;
    private static String maxActive;
    private static String maxWait;
    static{
        try {
            //获取数据库连接信息
            properties.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
            driver=properties.getProperty("jdbc.driver");
            url=properties.getProperty("jdbc.url");
            user=properties.getProperty("jdbc.user");
            pwd=properties.getProperty("jdbc.pwd");
            //获取连接池信息
            initialSize=properties.getProperty("dataSource.initialSize");
            maxIdle=properties.getProperty("dataSource.maxIdle");
            minIdle=properties.getProperty("dataSource.maxIdle");
            maxActive=properties.getProperty("dataSource.maxIdle");
            maxWait=properties.getProperty("dataSource.maxWait");
            //设置连接池
            basicDataSource.setDriverClassName(driver);
            basicDataSource.setUrl(url);
            basicDataSource.setUsername(user);
            basicDataSource.setPassword(pwd);
            basicDataSource.setInitialSize(Integer.parseInt(initialSize));
            basicDataSource.setMinIdle(Integer.parseInt(minIdle));
            basicDataSource.setMaxIdle(Integer.parseInt(maxIdle));
            basicDataSource.setMaxActive(Integer.parseInt(maxActive));
            basicDataSource.setMaxWait(Integer.parseInt(maxWait));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //从连接池获取连接
    public static Connection getConnection() throws SQLException{
        Connection con=basicDataSource.getConnection();
        return con;
    }
    //关闭连接
    public static void closeConnection(Connection con,Statement statement,ResultSet rs) throws SQLException{
        if(rs!=null){
            rs.close();
        }
        if(statement!=null){
            statement.close();
        }
        if(con!=null){
            con.close();
        }
    }
}